<?php

namespace app\service;

use app\Http;
use think\facade\Config;

class Elasticsearch {
    /**
     * @param string $indexName
     * @param string $tableName
     * @param $data
     * @param $id string ES中的id
     * @return mixed
     */
    public function add($indexName = 'default', $tableName = 'all', $data, $id) {
        $url = Config::get('common.es') . '/' . $indexName . '/' . $tableName . '/' . $id;
        $str = Http::curlPost($url, $data);
        return $str;
    }

    public function update($indexName = 'default', $tableName = 'all', $data, $id) {
        $data = [
            'doc' => $data
        ];
        $url = Config::get('common.es') . '/' . $indexName . '/' . $tableName . '/' . $id . '/_update';
        $str = Http::curlPost($url, $data);
        return $str;
    }

    public function delete($indexName = 'default', $tableName = 'all', $id) {
        $url = Config::get('common.es') . '/' . $indexName . '/' . $tableName . '/' . $id;
        $str = Http::curlDelete($url);
        return $str;
    }

    public function search($indexName, $tableName, $query, $from, $size, $sort = ['id' => 'desc'], $excludes = ['content']) {
        $url = Config::get('common.es') . '/' . $indexName . '/_search';
        $array = [];
        $count = 0;
        $data = [
            'from' => $from,
            'size' => $size,
            'sort' => $sort,
            'query' => $query,
        ];
        if (!empty($excludes)) {
            $data['_source'] = [
                'excludes' => $excludes
            ];
        }
        $str = Http::curlPost($url, $data);
//        var_dump($url);
//        var_dump($data);
//        var_dump($str);
//        exit;

        if ($str) {
            if (isset($str['hits']) && $str['hits']['total'] > 0) {
                $count = $str['hits']['total']['value'];
                foreach ($str['hits']['hits'] as $val) {

                    if (isset($val['_source']['shares'])) {
                        $val['_source']['share'] = $val['_source']['shares'];
                        unset($val['_source']['shares']);
                    }

                    array_push($array, $val['_source']);
                }
            }
        }

        return ['count' => $count, 'data' => $array];
    }


}
